// 检查无障碍服务是否已经启用，如果没有启用则跳转到无障碍服务启用界面，并等待无障碍服务启动；
auto.waitFor();

// 打开纷玩岛app
app.launchApp("秀动");
openConsole();
console.setTitle("秀动脚本已开启 go!", "#ff11ee00", 30);

// 秀动红米K30S确认选票坐标，建议配置（不配置时仍会寻找“确认”按钮进行点击，但可能会出现点击失败的情况）
// const ConfirmX = 911;
// const ConfirmY = 2153;
// k70
const ConfirmX = 911;
const ConfirmY = 2450;
// 是否在测试调试
var isDebug = false;
// 调试模式下的模拟票档自动选择的点击坐标
const debugTicketClickX = 780;
const debugTicketClickY = 150;
console.log("准备抢票");

main();

function getSellTime() {
    var sellTime = rawInput("请输入抢票时间(按照默认格式)", "08-12 13:00");
    if (sellTime == null || sellTime.trim() == '') {
        alert("请输入抢票时间!");
        return getSellTime();
    }
    return sellTime;
}

function main() {
    console.log('脚本运行时间', new Date().toLocaleString());
    console.log("已经进入待抢票界面，请确保已经预约和预填信息！！！");
    
    var month;
    var day;
    var hour;
    var minute;

    var inputTime = getSellTime();
    console.log("输入的抢票时间：" + inputTime);
    var times = inputTime.split(" ");
    var time1 = times[0];
    var time2 = times[1];
    var monthDay = time1.split("-");
    month = monthDay[0] - 1;
    day = monthDay[1];
    var hourMinute = time2.split(":");
    hour = hourMinute[0];
    minute = hourMinute[1];

    // 设置开抢时间
    var year = new Date().getFullYear();
    var second = 0;
    var msecond = 0;
    var startTimestamp = new Date(year, month, day, hour, minute, second, msecond).getTime();
    // 提前2s开始点击
    startTimestamp = startTimestamp - 2000;
    var startTime = convertToTime(startTimestamp);
    console.log("开抢时间：", startTime);

    console.log("等待开抢...");
    console.log("正式抢票模式！");

    // 循环等待
    while (true) {
        var damaiTimestamp = getDamaiTimestamp();
        if (damaiTimestamp >= startTimestamp) {
            break;
        }
    }

    if (!isDebug) {
        let cnt = 0;
        const maxCnt = 100;

        while (cnt < maxCnt) {
            cnt++;

            // 获取当前时间戳
            var damaiTimestamp = getDamaiTimestamp();

            if (descContains("刷新").exists()) {
                descContains("刷新").findOne().click();
            }

            click(ConfirmX, ConfirmY);

            if (text('立即购票').exists()) {
                text('立即购票').click();
            } else if (text('立即购买').exists()) {
                text('立即购买').click();
            }

            if (textContains("待支付").exists() || textContains("立即支付").exists()) {
                console.log("抢票成功啦！！！");
                break; // 抢票成功,退出循环
            } else {
                console.log("正式模式，已点击次数：" + cnt);
            }
        }
    } else {
        console.log("调试模式，不点击支付按钮");
    }

    console.log("结束时间：" + convertToTime(damaiTimestamp));
}

/**
 * @returns 大麦服务器时间戳
 */
function getDamaiTimestamp() {
    return JSON.parse(http.get("https://mtop.damai.cn/gw/mtop.common.getTimestamp/", {
        headers: {
            'Host': 'mtop.damai.cn',
            'Content-Type': 'application/json;charset=utf-8',
            'Accept': '*/*',
            'User-Agent': 'floattime/1.1.1 (iPhone; iOS 15.6; Scale/3.00)',
            'Accept-Language': 'zh-Hans-CN;q=1, en-CN;q=0.9',
            'Accept-Encoding': 'gzip, deflate, br',
            'Connection': 'keep-alive'
        }
    }).body.string()).data.t;
}

/**
 * @param {时间戳} timestamp
 * @returns ISO 8601 格式的北京时间
 */
function convertToTime(timestamp) {
    var date = new Date(Number(timestamp));
    var year = date.getUTCFullYear();
    var month = (date.getUTCMonth() + 1).toString().padStart(2, "0");
    var day = date.getUTCDate().toString().padStart(2, "0");
    var hours = (date.getUTCHours() + 8).toString().padStart(2, "0");
    var minutes = date.getUTCMinutes().toString().padStart(2, "0");
    var seconds = date.getUTCSeconds().toString().padStart(2, "0");
    var milliseconds = date.getUTCMilliseconds().toString().padStart(3, "0");
    var iso8601 = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
    return iso8601;
}
